class AudioPlayer {
    constructor() {
        this.audio = document.getElementById('audio');
        this.audioFile = document.getElementById('audioFile');
        this.lyricsContainer = document.getElementById('lyricsContainer');
        this.lyrics = [];
        this.currentLyricIndex = -1;

        this.init();
    }

    init() {
        this.audioFile.addEventListener('change', (e) => this.handleFileSelect(e));
        this.audio.addEventListener('timeupdate', () => this.updateLyrics());
    }

    handleFileSelect(event) {
        const audioFile = event.target.files[0];
        if (!audioFile) return;

        // 更新歌曲信息
        const fileName = audioFile.name.replace(/\.[^/.]+$/, "");
        document.getElementById('songTitle').textContent = fileName;
        document.getElementById('songArtist').textContent = '本地音频';

        // 创建音频文件的URL
        const audioUrl = URL.createObjectURL(audioFile);
        this.audio.src = audioUrl;

        // 尝试加载同名的LRC文件
        const lrcFile = event.target.files[0].name.replace(/\.[^/.]+$/, ".lrc");
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.lrc';
        input.style.display = 'none';

        input.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                this.loadLrcFile(file);
            }
        });

        document.body.appendChild(input);
        input.click();
        document.body.removeChild(input);
    }

    loadLrcFile(file) {
        const reader = new FileReader();
        reader.onload = async (e) => {
            let lrcText = e.target.result;
            
            // 检测是否为乱码并尝试转换编码
            if (this.isGarbledText(lrcText)) {
                // 尝试使用 GBK 编码重新读取
                lrcText = await this.readFileWithEncoding(file, 'gbk');
            }
            
            this.parseLrc(lrcText);
            this.renderLyrics();
        };
        reader.readAsText(file, 'utf-8'); // 首先尝试 UTF-8
    }

    // 检查文本是否为乱码
    isGarbledText(text) {
        // 检查是否包含常见乱码字符
        const garbledPattern = /[\ufffd\u0000-\u0008\u00b7\u00a7\u2022]/g;
        
        // 检查中文字符比例
        const chinesePattern = /[\u4e00-\u9fa5]/g;
        const chineseChars = text.match(chinesePattern);
        const totalChars = text.length;
        
        // 如果文本中包含乱码字符或中文字符比例异常低，则可能是编码问题
        return garbledPattern.test(text) || (totalChars > 0 && (!chineseChars || chineseChars.length / totalChars < 0.1));
    }

    // 使用指定编码读取文件
    async readFileWithEncoding(file, encoding) {
        // 使用 TextDecoder 来处理不同编码
        const buffer = await file.arrayBuffer();
        let decoder;
        
        try {
            if (encoding.toLowerCase() === 'gbk') {
                // 如果浏览器支持 GBK 编码
                decoder = new TextDecoder('gbk');
            } else {
                decoder = new TextDecoder(encoding);
            }
            return decoder.decode(buffer);
        } catch (error) {
            console.error('编码转换失败:', error);
            // 如果转换失败，尝试使用替代方案
            return this.convertGBKToUTF8(buffer);
        }
    }

    // GBK 到 UTF-8 的转换（需要引入外部库）
    convertGBKToUTF8(buffer) {
        // 这里我们需要在 HTML 中引入 GBK.js 库
        if (typeof GBK !== 'undefined') {
            try {
                return GBK.decode(new Uint8Array(buffer));
            } catch (error) {
                console.error('GBK 转换失败:', error);
                return '';
            }
        }
        return '';
    }

    parseLrc(lrcText) {
        this.lyrics = [];
        const lines = lrcText.split('\n');
        const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/;

        lines.forEach(line => {
            const match = timeRegex.exec(line);
            if (match) {
                const minutes = parseInt(match[1]);
                const seconds = parseInt(match[2]);
                const milliseconds = parseInt(match[3]);
                const time = minutes * 60 + seconds + milliseconds / 1000;
                const text = line.replace(timeRegex, '').trim();

                if (text) {
                    this.lyrics.push({
                        time,
                        text
                    });
                }
            }
        });

        this.lyrics.sort((a, b) => a.time - b.time);
    }

    renderLyrics() {
        this.lyricsContainer.innerHTML = '';
        this.lyrics.forEach((lyric, index) => {
            const div = document.createElement('div');
            div.className = 'lyric-line';
            div.textContent = lyric.text;
            div.setAttribute('data-index', index);
            this.lyricsContainer.appendChild(div);
        });
    }

    updateLyrics() {
        const currentTime = this.audio.currentTime;
        let index = this.lyrics.findIndex(lyric => lyric.time > currentTime);
        
        if (index === -1) {
            index = this.lyrics.length;
        }
        index = Math.max(0, index - 1);

        if (this.currentLyricIndex !== index) {
            const oldActive = document.querySelector('.lyric-line.active');
            if (oldActive) {
                oldActive.classList.remove('active');
            }

            const currentLine = document.querySelector(`.lyric-line[data-index="${index}"]`);
            if (currentLine) {
                currentLine.classList.add('active');
                currentLine.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }

            this.currentLyricIndex = index;
        }
    }
}

// 初始化播放器
new AudioPlayer();